package de.ishuo.netzclubminutecounter;

import java.awt.FileDialog;
import java.io.File;
import java.io.FilenameFilter;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 * Helper class providing often used functionality concerning
 * file opening / choosing / exception handling.
 */
public class FileChooser {
	
	private static String[] SUPPORTED_FORMATS = new String[] { "pdf", "PDF" };
	
	static class AcceptedFileNameFilter implements FilenameFilter {

		@Override
		public boolean accept(File dir, String name) {
			return name.toLowerCase().endsWith("pdf");
		}
	}
	
	/**
	 * Creates a File Open Dialog and returns the chosen file if the user does,
	 * or null if the user chooses "cancel" or the file doesn't exist
	 * 
	 * @return absolute path of the chosen file
	 */
	public static String chooseFile(JFrame frame) {
		if (Main.isOnMac()) {
			// On the Mac platform the AWT implementation is preferred
			return chooseFileOnMac(frame);
		} else {
			return chooseFileOnOtherPlatforms(frame);
		}
	}

	private static String chooseFileOnMac(JFrame frame) {
		FileDialog dialog = new FileDialog(frame, "Open", FileDialog.LOAD);
		dialog.setFilenameFilter(new AcceptedFileNameFilter());
		// TODO store last used directory
//			dialog.setDirectory(state.getPresentationDirectory());
		dialog.setVisible(true);
		return dialog.getFile() == null ? "" : dialog.getDirectory() + dialog.getFile();
	}

	private static String chooseFileOnOtherPlatforms(JFrame frame) {
		JFileChooser chooser = createFileChooser();

		int openState = chooser.showOpenDialog(frame);
		if (openState == JFileChooser.APPROVE_OPTION) {
			// If not canceled:
			return chooser.getSelectedFile().getAbsolutePath();
		}
		return "";
	}


	private static JFileChooser createFileChooser() {
		// TODO store last used directory
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		
		FileNameExtensionFilter fileFilter = new FileNameExtensionFilter(
				"Netzclub Entgeltnachweis", SUPPORTED_FORMATS);
		chooser.addChoosableFileFilter(fileFilter);
		chooser.setFileFilter(fileFilter);
		return chooser;
	}


}
